package com.hikvision.open.app.ui.download

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Observer
import com.hikvision.hatomplayer.PlayCallback
import com.hikvision.open.app.ui.local.LocalVideoPlayActivity
import com.hikvision.open.app.utils.PermissionHelper
import com.hikvision.open.app.utils.inflate
import com.hikvision.open.app.widget.PermissionDialog
import hik.sdk.demo.R
import hik.sdk.demo.databinding.ActivityDownloadBinding

/**
 * <p> 录像下载界面 </p>
 * @author 段自航 2021/7/14 10:20
 * @version V1.0
 */
class DownloadActivity : AppCompatActivity(), View.OnClickListener {
    private val viewModel by viewModels<DownloadViewModel>()
    private val viewBinding: ActivityDownloadBinding by inflate()
    private var downloadUrl =
        "rtsp://pnp-video5.zt-express.com:559/openUrl/q22qfvO"
    private var startTime = "2024-06-11T20:10:39.000+08:00"
    private var endTime = "2024-06-11T20:11:39.000+08:00"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(viewBinding.root)
        viewBinding.backImage.setOnClickListener {
            finish()
        }
        viewBinding.downloadUrlEdit.setText(downloadUrl)
        viewBinding.startTimeEdit.setText(startTime)
        viewBinding.endTimeEdit.setText(endTime)
        viewBinding.startDownloadButton.setOnClickListener(this)
        viewBinding.stopDownloadButton.setOnClickListener(this)
        viewModel.saveResult.observe(this) {
            if (it == null) {
                return@observe
            }
            when (it) {
                0 -> {
                    Toast.makeText(this, "录像转码中", Toast.LENGTH_SHORT).show()
                }

                1 -> {
                    showLocalPlayDialog()
                }

                -1 -> {
                    Toast.makeText(this, "录像转码失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
        viewModel.downloadResult.observe(this, Observer {
            when (it.status) {
                PlayCallback.Status.SUCCESS -> {
                    Toast.makeText(this, "下载中......", Toast.LENGTH_SHORT).show()
                }

                PlayCallback.Status.FAILED -> {
                    Toast.makeText(this, "下载开启失败", Toast.LENGTH_SHORT).show()
                }

                PlayCallback.Status.EXCEPTION -> {
                    Toast.makeText(this, "下载异常", Toast.LENGTH_SHORT).show()
                }

                PlayCallback.Status.FINISH -> {
                    Toast.makeText(
                        this,
                        "下载结束, 文件存储地址: ${viewModel.filePath}, 开始转码",
                        Toast.LENGTH_SHORT
                    ).show()
                }

                else -> {

                }
            }
        })
    }

    private fun showLocalPlayDialog() {
        val dialog = AlertDialog.Builder(this)
            .setCancelable(true)
            .setMessage("是否播放本地录像？")
            .setNegativeButton(
                "取消"
            ) { dialog, _ ->
                dialog.dismiss()
            }
            .setNeutralButton("确定") { dialog, _ ->
                dialog.dismiss()
                val intent = Intent(this, LocalVideoPlayActivity::class.java)
                val localFileUrl = viewModel.filePath
                intent.putExtra(LocalVideoPlayActivity.MEDIA_FILE_PATH, localFileUrl)
                startActivity(intent)
            }
            .create()
        dialog.show()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.startDownloadButton -> {
                startDownload()
            }

            R.id.stopDownloadButton -> {
                stopDownload()
            }
        }
    }

    /**
     * 开启下载
     */
    private fun startDownload() {
        val downloadUrl = viewBinding.downloadUrlEdit.text.toString()
        if (downloadUrl.isEmpty()) {
            Toast.makeText(this, "请输入下载Url", Toast.LENGTH_SHORT).show()
            return
        }
        val startTime = viewBinding.startTimeEdit.text.toString()
        val endTime = viewBinding.endTimeEdit.text.toString()

        //进行权限判断
        if (PermissionHelper.isGranted(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            viewModel.startDownload(downloadUrl, startTime, endTime, "ssss")
        } else {
            //请求权限
            PermissionHelper.requestStoragePermission(this) { allGranted ->
                if (allGranted) {
                    viewModel.startDownload(downloadUrl, startTime, endTime, "ssss")
                }
            }
        }

    }

    /**
     * 停止下载
     */
    private fun stopDownload() {
        viewModel.stopDownload()
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        PermissionHelper.handlePermissionsResult(requestCode, permissions, grantResults)
    }
}